<template>
  <view class="detail-container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="back-btn" @click="navigateBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
      </view>
      <text class="navbar-title">公司详情</text>
      <view class="empty-space"></view>
    </view>
    
    <!-- 公司基本信息 -->
    <view class="company-header">
      <image :src="company.logo" class="header-logo" mode="widthFix"></image>
      <view class="header-info">
        <view class="header-name-rank">
          <text class="header-name">{{ company.name }}</text>
          <view class="header-rank" :class="rankClass">
            排名 #{{ company.rank }}
          </view>
        </view>
        <text class="header-desc">{{ company.description }}</text>
        <view class="header-category">
          <text class="category-label">所属类目：</text>
          <text class="category-value">{{ company.categoryName }}</text>
        </view>
        <view class="header-score">
          <text class="score-label">评分：</text>
          <text class="score-value">{{ company.score }}</text>
        </view>
      </view>
    </view>
    
    <!-- 公司介绍 -->
    <view class="company-intro">
      <view class="section-title">公司介绍</view>
      <view class="intro-content">
        <text>{{ company.introduction || '暂无公司介绍' }}</text>
      </view>
    </view>
    
    <!-- 评价功能 -->
    <view class="evaluation-section">
      <view class="section-title">用户评价</view>
      
      <!-- 评价表单 -->
      <view class="evaluation-form">
        <view class="rating-section">
          <text class="rating-label">评分：</text>
          <view class="rating-stars">
            <u-rate 
              :value="currentRating / 10" 
              @change="onRatingChange"
              :count="10"
              :size="24"
              active-color="#ff4d4f"
            ></u-rate>
            <text class="rating-value">{{ currentRating }}/100</text>
          </view>
        </view>
        
        <view class="comment-section">
          <text class="comment-label">评价内容：</text>
          <textarea 
            v-model="commentContent" 
            class="comment-input"
            placeholder="请输入您的评价内容..."
            :maxlength="500"
            :auto-height="true"
          ></textarea>
          <text class="comment-length">{{ commentContent.length }}/500</text>
        </view>
        
        <button class="submit-btn" @click="submitEvaluation">
          <text>提交评价</text>
        </button>
      </view>
    </view>
    
    <!-- 评价列表 -->
    <view class="evaluation-list-section">
      <view class="section-title">
        评价列表
        <text class="evaluation-count">({{ totalEvaluations }})</text>
      </view>
      
      <view v-if="evaluations.length > 0" class="evaluation-list">
        <view class="evaluation-item" v-for="evaluation in evaluations" :key="evaluation.id">
          <view class="evaluation-header">
            <view class="user-info">
              <image :src="evaluation.avatar || defaultAvatar" class="user-avatar" mode="aspectFill"></image>
              <text class="user-name">{{ evaluation.username }}</text>
            </view>
            <view class="evaluation-rating">
              <u-rate 
                :value="evaluation.rating / 10" 
                :count="10"
                :size="16"
                active-color="#ff4d4f"
                :disabled="true"
              ></u-rate>
              <text class="rating-text">{{ evaluation.rating }}/100</text>
            </view>
          </view>
          <view class="evaluation-content">
            <text>{{ evaluation.comment }}</text>
          </view>
          <view class="evaluation-meta">
            <text class="evaluation-time">{{ formatTime(evaluation.createdAt) }}</text>
          </view>
        </view>
      </view>
      
      <view v-else class="no-evaluations">
        <u-icon name="chat" size="60" color="#ddd" class="no-evaluations-icon"></u-icon>
        <text class="no-evaluations-text">暂无评价</text>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMoreEvaluations && !isLoadingEvaluations">
        <button class="load-more-btn" @click="loadMoreEvaluations">
          <text>加载更多</text>
        </button>
      </view>
      
      <!-- 没有更多数据 -->
      <view class="no-more" v-else-if="!hasMoreEvaluations && evaluations.length > 0 && !isLoadingEvaluations">
        <text class="no-more-text">没有更多评价了</text>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="isLoadingEvaluations">
        <u-loading-icon mode="circle" :size="20" color="#409eff"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <view class="products-section">
      <view class="section-title">
        商品列表
        <text class="product-count">({{ company.productLength || 0 }})</text>
      </view>
      
      <view v-if="company.products && company.products.length > 0" class="products-grid">
        <view 
          class="product-item" 
          v-for="product in company.products" 
          :key="product.id"
          @click="navigateToProductDetail(product)"
        >
          <image :src="product.image" class="product-image" mode="aspectFill"></image>
          <text class="product-name">{{ product.name }}</text>
          <text class="product-price">
            {{ product.price === 0 ? '免费' : product.price === '面议' ? '面议' : '¥' + product.price }}
          </text>
        </view>
      </view>
      
      <view v-else class="no-products">
        <u-icon name="list" size="60" color="#ddd" class="no-products-icon"></u-icon>
        <text class="no-products-text">该公司暂无商品信息</text>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {
      company: {},
      rankClass: '',
      currentRating: 50, // 默认评分
      commentContent: '',
      evaluations: [], // 评价列表
      allEvaluations: [], // 所有评价数据
      defaultAvatar: 'https://img.alicdn.com/imgextra/i1/O1CN01Zp9vLq1UQyq9q9q9q_!!6000000002534-2-tps.png', // 默认头像
      categories: [
        { id: 'tech', name: '科技' },
        { id: 'finance', name: '金融' },
        { id: 'retail', name: '零售' },
        { id: 'healthcare', name: '医疗健康' },
        { id: 'education', name: '教育' }
      ],
      // 分页相关
      evaluationPage: 1,
      evaluationPageSize: 10,
      totalEvaluations: 0,
      hasMoreEvaluations: true,
      isLoadingEvaluations: false
    };
  },
  computed:{
  	...mapState(['userInfo', "appProperties"]),
  },
  onLoad() {
    // 获取从首页传递的公司信息
    this.company = getApp().globalData.currentCompany || {};
    this.getRankingDetail();
    
    // 设置排名样式
    if (this.company.rank === 1) {
      this.rankClass = 'rank-first';
    } else if (this.company.rank === 2) {
      this.rankClass = 'rank-second';
    } else if (this.company.rank === 3) {
      this.rankClass = 'rank-third';
    }
    
    // 获取评价列表
    this.getEvaluations(true);
  },
  
  methods: {
    navigateBack() {
      uni.navigateBack();
    },
    
    async getRankingDetail() {
      try {
        const response = await this.$request(`api/v1/companies/rankDetail/${this.company.id}`, 'GET');
        if (response.code === 200) {
          this.company.products = response.data.products || [];
          this.company.productLength = this.company.products.length;
        }
      } catch (error) {
        console.error('获取公司数据失败:', error);
        this.error = '公司数据加载失败，请检查网络连接';
      }
    },
    
    // 获取评价列表（分页）
    async getEvaluations(reset = true) {
      if (reset) {
        this.evaluationPage = 1;
        this.evaluations = [];
        this.allEvaluations = [];
        this.isLoadingEvaluations = true;
      } else {
        this.isLoadingEvaluations = true;
      }
      
      try {
        const params = {
          companyId: this.company.id,
          pageNum: this.evaluationPage,
          pageSize: this.evaluationPageSize
        };
        
        const response = await this.$request('api/v1/evaluations/list', 'GET', params);
        if (response.code === 200) {
          const { rows, total } = response;
          this.totalEvaluations = total;
          this.hasMoreEvaluations = rows.length === this.evaluationPageSize;
          
          if (reset) {
            this.evaluations = rows;
          } else {
            this.evaluations = [...this.evaluations, ...rows];
          }
          
          // 更新所有评价数据
          this.allEvaluations = [...this.evaluations];
        } else {
          console.error('获取评价列表失败:', response.msg);
          if (reset) {
            this.evaluations = [];
            this.allEvaluations = [];
          }
        }
      } catch (error) {
        console.error('获取评价列表失败:', error);
        if (reset) {
          this.evaluations = [];
          this.allEvaluations = [];
        }
      } finally {
        this.isLoadingEvaluations = false;
      }
    },
    
    // 加载更多评价
    loadMoreEvaluations() {
      if (!this.hasMoreEvaluations || this.isLoadingEvaluations) return;
      
      this.evaluationPage++;
      this.getEvaluations(false);
    },
    
    // 评分变化处理
    onRatingChange(value) {
      this.currentRating = value * 10; // 转换为0-100分制
    },
    
    // 提交评价
    async submitEvaluation() {
	  if(!this.userInfo){
	  	uni.navigateTo({
	  	  url: `/pages/login/login`
	  	});
	  		return
	  } 	
      if (!this.commentContent.trim()) {
        uni.showToast({
          title: '请输入评价内容',
          icon: 'none'
        });
        return;
      }
      
      if (this.currentRating < 1) {
        uni.showToast({
          title: '请给出评分',
          icon: 'none'
        });
        return;
      }
      
      try {
        const evaluationData = {
          companyId: this.company.id,
          rating: this.currentRating,
          comment: this.commentContent,
		  userId:this.userInfo.appUserId
        };
        
        const response = await this.$request('api/v1/evaluations', 'POST', evaluationData);
        if (response.code === 200) {
          uni.showToast({
            title: '评价提交成功',
            icon: 'none',
            duration: 1500
          });
          
          // 清空表单
          this.commentContent = '';
          this.currentRating = 50;
          
          // 重新获取评价列表（重置分页）
          this.getEvaluations(true);
        } else {
          uni.showToast({
            title: response.msg || '提交失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('提交评价失败:', error);
        uni.showToast({
          title: '提交失败，请检查网络连接',
          icon: 'none'
        });
      }
    },
    
    // 获取类目名称
    getCategoryName(categoryId) {
      const category = this.categories.find(cat => cat.id === categoryId);
      return category ? category.name : '未知';
    },
    
    // 格式化时间
    formatTime(timeString) {
      if (!timeString) return '';
      
      const date = new Date(timeString);
      const now = new Date();
      const diff = now - date;
      
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      if (days > 0) {
        return `${days}天前`;
      }
      
      const hours = Math.floor(diff / (1000 * 60 * 60));
      if (hours > 0) {
        return `${hours}小时前`;
      }
      
      const minutes = Math.floor(diff / (1000 * 60));
      if (minutes > 0) {
        return `${minutes}分钟前`;
      }
      
      return '刚刚';
    },
    
    // 跳转到商品详情页
    navigateToProductDetail(product) {
      const imagesStr = JSON.stringify(product.images);
      // 跳转到产品详情页
      uni.navigateTo({
        url: `/pages/goods/detail?id=${product.id}&images=${encodeURIComponent(imagesStr)}`
      });
    }
  }
};
</script>

<style scoped>
.detail-container {
  background-color: #f5f5f7;
  min-height: 100vh;
  padding-top: 44px; /* 预留导航栏高度 */
}

/* 导航栏样式 */
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  z-index: 999;
}

.back-btn {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.empty-space {
  width: 30px;
  height: 30px;
}

/* 公司头部信息 */
.company-header {
  display: flex;
  padding: 20px 16px;
  background-color: #ffffff;
  margin-bottom: 10px;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.header-logo {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  margin-right: 16px;
  border: 2px solid #f0f2f5;
  box-sizing: border-box;
}

.header-info {
  flex: 1;
  overflow: hidden;
}

.header-name-rank {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.header-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-rank {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  color: #ffffff;
  background-color: #999;
  flex-shrink: 0;
}

.header-rank.rank-first {
  background: linear-gradient(135deg, #ffd700, #ffa500);
}

.header-rank.rank-second {
  background: linear-gradient(135deg, #c0c0c0, #a9a9a9);
}

.header-rank.rank-third {
  background: linear-gradient(135deg, #cd7f32, #b87333);
}

.header-desc {
  font-size: 14px;
  color: #666;
  display: block;
  margin-bottom: 8px;
  line-height: 1.4;
}

.header-category {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.category-label {
  font-size: 13px;
  color: #666;
}

.category-value {
  font-size: 13px;
  color: #409eff;
  font-weight: 500;
  background-color: #e6f7ff;
  padding: 2px 8px;
  border-radius: 12px;
  margin-left: 4px;
}

.header-score {
  display: flex;
  align-items: center;
}

.score-label {
  font-size: 14px;
  color: #666;
}

.score-value {
  font-size: 16px;
  font-weight: bold;
  color: #ff4d4f;
}

/* 通用区块标题 */
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding: 16px;
  padding-bottom: 10px;
  background-color: #ffffff;
}

/* 公司介绍 */
.company-intro {
  background-color: #ffffff;
  margin-bottom: 10px;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.intro-content {
  padding: 0 16px 16px;
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

/* 评价功能 */
.evaluation-section {
  background-color: #ffffff;
  margin-bottom: 10px;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.evaluation-form {
  padding: 0 16px 16px;
}

.rating-section {
  margin-bottom: 16px;
}

.rating-label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.rating-stars {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rating-value {
  font-size: 14px;
  color: #ff4d4f;
  font-weight: bold;
  margin-left: 10px;
}

.comment-section {
  margin-bottom: 16px;
}

.comment-label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.comment-input {
  width: 94%;
  min-height: 80px;
  padding: 12px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
  background-color: #f9f9f9;
}

.comment-length {
  display: block;
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.submit-btn {
  width: 100%;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 12px;
  font-size: 16px;
  font-weight: 500;
}

/* 评价列表 */
.evaluation-list-section {
  background-color: #ffffff;
  margin-bottom: 10px;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.evaluation-count {
  font-size: 14px;
  font-weight: normal;
  color: #999;
  margin-left: 8px;
}

.evaluation-list {
  padding: 0 16px 16px;
}

.evaluation-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.evaluation-item:last-child {
  border-bottom: none;
}

.evaluation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #f0f2f5;
}

.user-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.evaluation-rating {
  display: flex;
  align-items: center;
  gap: 5px;
}

.rating-text {
  font-size: 12px;
  color: #ff4d4f;
  font-weight: bold;
}

.evaluation-content {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 8px;
}

.evaluation-meta {
  display: flex;
  justify-content: flex-end;
}

.evaluation-time {
  font-size: 12px;
  color: #999;
}

.no-evaluations {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 16px;
  text-align: center;
}

.no-evaluations-icon {
  margin-bottom: 15px;
  opacity: 0.6;
}

.no-evaluations-text {
  font-size: 14px;
  color: #999;
}

/* 加载更多样式 */
.load-more {
  display: flex;
  justify-content: center;
  padding: 20px 16px;
}

.load-more-btn {
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 20px;
  padding: 10px 24px;
  font-size: 14px;
}

/* 没有更多数据样式 */
.no-more {
  display: flex;
  justify-content: center;
  padding: 20px 16px;
}

.no-more-text {
  color: #999;
  font-size: 14px;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 16px;
  gap: 10px;
}

.loading-text {
  font-size: 14px;
  color: #666;
}

/* 商品列表 */
.products-section {
  background-color: #ffffff;
  padding-bottom: 16px;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.product-count {
  font-size: 14px;
  font-weight: normal;
  color: #999;
  margin-left: 8px;
}

.products-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  padding: 0 16px;
}

.product-item {
  background-color: #f9f9f9;
  border-radius: 12px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.product-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 8px;
  background-color: #f0f2f5;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
}

.product-price {
  font-size: 14px;
  color: #ff4d4f;
  font-weight: bold;
}

.no-products {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 16px;
  text-align: center;
}

.no-products-icon {
  margin-bottom: 15px;
  opacity: 0.6;
}

.no-products-text {
  font-size: 14px;
  color: #999;
}

/* 响应式调整 */
@media (max-width: 375px) {
  .company-header {
    padding: 16px;
  }
  
  .header-logo {
    width: 70px;
    height: 70px;
  }
  
  .header-name {
    font-size: 16px;
  }
  
  .products-grid {
    gap: 12px;
  }
  
  .product-item {
    padding: 10px;
  }
  
  .product-image {
    height: 100px;
  }
  
  .product-name {
    font-size: 13px;
  }
  
  .evaluation-form {
    padding: 0 12px 12px;
  }
  
  .comment-input {
    padding: 10px;
    font-size: 13px;
  }
  
  .load-more-btn {
    padding: 8px 20px;
    font-size: 13px;
  }
}
</style>



